// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()
const axios = require('axios')
const URL = 'https://apis.imooc.com/personalized?icode=9FAE7B2914FFAF04'
const playlistCollection = db.collection('playlist')
const MAX_LIMIT = 100

// 定时获取歌单数据，并插入云数据库（在config.json配置触发时机）
exports.main = async (event, context) => {
    // 1.获取云数据库中的歌单数据（突破获取数据条数的限制）
    const countResult = await playlistCollection.count()
    const total = countResult.total
    const batchTimes = Math.ceil(total / MAX_LIMIT)
    const tasks = []
    let list = {data: []}

    for (let i = 0; i < batchTimes; i++) {
        let promise = playlistCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
        tasks.push(promise)
    }

    if (tasks.length > 0) {
        list = (await Promise.all(tasks)).reduce((acc, cur) => {
            return {
                data: acc.data.concat(cur.data)
            }
        })
    }

    // 2.通过axios请求第三方接口，获取新的歌单数据
    const { data } = await axios.get(URL)
    if (data.code >= 1000) return 0
    const playlist = data.result
    const newData = []

    for (let i = 0, len1 = playlist.length; i < len1; i++) {
        let flag = true
        for (let j = 0, len2 = list.data.length; j < len2; j++) {
            if (playlist[i].id === list.data[j].id) {
                flag = false
                break
            }
        }
        if (flag) {
            let curPlaylist = playlist[i]
            curPlaylist.createTime = db.serverDate()
            newData.push(curPlaylist)
        }
    }

    if (newData.length > 0) {
        await playlistCollection.add({
            data: newData
        }).then(res => {
            console.log('插入成功')
        }).catch(err => {
            console.log(err)
            console.error('插入失败')
        })
    }

    return newData.length
}